﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNet.Common.NHibernateUtil;
using NHibernate;
using ZLCMS.Data.Model;
using NHibernate.Criterion;
using DotNet.Common.NHibernateUtil.QueryFilter;
using NHibernate.Transform;
using System.Collections;

namespace ZLCMS.Web.Product
{
    public partial class ProductList : System.Web.UI.Page
    {
        public string _categoryId;
        public ShopProductInfo _productInfo;
        public IList<ShopCategory> CategoryList;
        public string _orderBy;
        public string _msg_title;

        protected void Page_Load(object sender, EventArgs e)
        {
            _categoryId =string.IsNullOrEmpty( Request["categoryid"])? "0" : Request["categoryid"];
            _orderBy =string.IsNullOrEmpty( Request["orderby"]) ? "" : Request["orderby"];
         
            CategorySearchPropertyItems1.CategoryId = Convert.ToInt32( _categoryId);
            CategorySearchPropertyItems1.TagId = Request["tagid"];

            //绑定产品信息列表
            int currentPageIndex = string.IsNullOrEmpty(Request[anp_list.UrlPageIndexName]) ? 1 : int.Parse(Request[anp_list.UrlPageIndexName]);
            anp_list.PageSize = string.IsNullOrEmpty(Request["pagen"]) ? 16 : int.Parse(Request["pagen"]);

            rptBind(currentPageIndex, anp_list.PageSize);

            return;
        }

        #region 绑定产品信息列表
        /// <summary>
        /// 绑定产品信息列表
        /// </summary>
        private void rptBind(int pageIndex, int pageSize)
        {
            string _asc =string.IsNullOrEmpty( Request["asc"] )? "" : Request["asc"];

            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                IList<ShopCategorySearchProperty> propertyList = session.CreateQuery("from ShopCategorySearchProperty where CategoryId=:cid order by Sort ").SetParameter("cid", _categoryId).List<ShopCategorySearchProperty>();

                CategorySearchPropertyItems1.PropertyList = propertyList;

               

                string fromSql = " from Shop_Product_Info where Owner_Account='admin'  and Kind='shop' and Status='1' ";
                if (_categoryId != "0")
                {
                    fromSql += " and type_prefix like :type_prefix ";
                }


                foreach (ShopCategorySearchProperty p in propertyList)
                {
                    if (!string.IsNullOrEmpty(Request[p.Id.ToString()]))
                    {
                        fromSql += "  and product_no in ( select product_no from shop_product_search_property_value where property_item_id =:s_" + p.Id;
                    }
                }
                foreach (ShopCategorySearchProperty p in propertyList)
                {
                    if (!string.IsNullOrEmpty(Request[p.Id.ToString()]))
                    {
                        fromSql += " ) ";
                    }
                }

                //if (!string.IsNullOrEmpty(Request["keyword"]) )
                //{
                //    fromSql += " and ( PRODUCT_NAME like '%" + Request["keyword"] + "%' or SHORT_DESC like '%" + Request["keyword"] + "%')";
                //}
                if (!string.IsNullOrEmpty(Request["keyword"]))
                {
                    fromSql += " and ( PRODUCT_NAME like :keyword or SHORT_DESC like :keyword )";
                }
                if (!string.IsNullOrEmpty(Request["tagid"]))
                {
                    fromSql += " and tag_ids like :tagids";
                }
                //获取记录总数
                ISQLQuery cntquery = session.CreateSQLQuery("select count(*)" + fromSql);

               
                if(_categoryId!="0")
                {
                    cntquery.SetParameter("type_prefix", "%\\_" + _categoryId + "\\_%");
                }
                if (!string.IsNullOrEmpty(Request["keyword"]))
                {
                    cntquery.SetParameter("keyword", "%" + Request["keyword"] + "%");

                }
                if (!string.IsNullOrEmpty(Request["tagid"]))
                {
                    cntquery.SetParameter("tagids", "%_" + Request["tagid"].Trim() + "_%");
                }
                foreach (ShopCategorySearchProperty p in propertyList)
                {
                    if (!string.IsNullOrEmpty(Request[p.Id.ToString()]))
                    {
                        cntquery.SetParameter("s_" + p.Id, Request[p.Id.ToString()]);
                    }
                }



                anp_list.RecordCount = Convert.ToInt32(cntquery.UniqueResult());


                //获取数据
                string select = " select * ";

                string order = " ";

                #region 判断排序方法
                if (_orderBy == "sellcount")//按销量排序
                {
                    order = " order by Sell_Count ";
                }
                else if (_orderBy == "saleprice")//按销售价排序
                {
                    order = " order by Sale_Price ";
                }
                else if (_orderBy == "addtime")//按上架时间排序
                {
                    order = " order by Add_Time ";
                }
                else if (_orderBy == "score")//按默认排序
                {
                    order = " order by Score ";
                }
                else if (_orderBy == "default"||_orderBy=="")//按默认排序
                {
                    order = " order by Id ";
                }
                if (_asc == "1")
                {
                    order += "  asc";
                }
                else
                {
                    order += "  desc";
                }

                #endregion


                ISQLQuery queryList = session.CreateSQLQuery(select + fromSql + order);

                if (_categoryId != "0")
                {
                    queryList.SetParameter("type_prefix", "%\\_" + _categoryId + "\\_%");
                }
                if (!string.IsNullOrEmpty(Request["keyword"]))
                {
                   queryList.SetParameter("keyword", "%"+Request["keyword"]+"%");
                
                }
                if (!string.IsNullOrEmpty(Request["tagid"]))
                {
                    queryList.SetParameter("tagids", "%_" + Request["tagid"].Trim() + "_%");
                }

                foreach (ShopCategorySearchProperty p in propertyList)
                {
                    if (!string.IsNullOrEmpty(Request[p.Id.ToString()]))
                    {
                        queryList.SetParameter("s_" + p.Id, int.Parse(Request[p.Id.ToString()]));
                    }
                }
              //IQuery iquery  =  queryList.SetFirstResult((pageIndex - 1) * pageSize).SetMaxResults(pageSize).SetResultTransformer(Transformers.AliasToEntityMap);

              //IList<Hashtable> proList = iquery.List<Hashtable>();
              //if (!string.IsNullOrEmpty(Request["tagid"])) {
              //  for (int i = proList.Count - 1; i >= 0; i--)
              //{
              //    bool exist = false;
              //    string tagIds = proList[i]["TAG_IDS"] as string;
              //    string[] tidArrey = tagIds.Split(',');
              //    foreach (string tid in tidArrey)
              //    {
              //        if (tid == Request["tagid"])
              //        {
              //            exist = true;
              //            ShopTagInfo tagInfo = session.Get<ShopTagInfo>(int.Parse(tid));
              //            if (tagInfo.Status == "0" || tagInfo.Status == "9" || tagInfo.BeginUseTime > DateTime.Now || tagInfo.EndUseTime < DateTime.Now)
              //            {
              //                exist = false;
              //            }
              //        }
              //    }
              //    if (!exist)
              //    {
              //        proList.Remove(proList[i]);
              //    }
              //}
              //}

                //rpt_pro.DataSource = proList;
                //  rpt_pro.DataBind();

                rpt_pro.DataSource = queryList.SetFirstResult((pageIndex - 1) * pageSize).SetMaxResults(pageSize).SetResultTransformer(Transformers.AliasToEntityMap).List();
                rpt_pro.DataBind();

            }
        }
        #endregion
    }
}